import 'dart:async';
import 'dart:convert';

import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class Login extends StatefulWidget {
  final String pageIndex;

  Login({String pageIndex}) : this.pageIndex = pageIndex;

  @override
  _LoginState createState() => _LoginState(pageIndex: pageIndex);
}

class _LoginState extends State<Login> {
  String pageIndex;
  Timer _timer;
  String title = 'gggg';

  int _countdownTime = 0;
  static const platform = const MethodChannel("getMethod4Flutter");

  var _scaffoldkey = new GlobalKey<ScaffoldState>();

  Future<Null> getMethod4Flutter(String method) async {
    try {
      await platform.invokeMethod(method);
    } on PlatformException {}
  }

  _LoginState({String pageIndex}) : this.pageIndex = pageIndex;
  TextEditingController _controllerName =
      TextEditingController.fromValue(TextEditingValue(text: ''));
  TextEditingController _controllerPass =
      TextEditingController.fromValue(TextEditingValue(text: ''));
  TextEditingController _controllerCode =
      TextEditingController.fromValue(TextEditingValue(text: ''));

  void startCountdownTimer() {
    const oneSec = const Duration(seconds: 1);

    var callback = (timer) => {
          setState(() {
            if (_countdownTime < 1) {
              _timer.cancel();
            } else {
              _countdownTime = _countdownTime - 1;
              print('_countdownTime:$_countdownTime');
            }
          })
        };

    _timer = Timer.periodic(oneSec, callback);
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  _getTitle() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      title = prefs.getString('name');
    });
  }

  @override
  void initState() {
//    _getTitle();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldkey,
      appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          title: Text(''),
          centerTitle: true,
          leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
              ),
              onPressed: () {
                Navigator.pop(context);
              })),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 42),
        child: ListView(
          children: <Widget>[
            Image.asset(
              'images/icon_launcher.png',
              width: 90,
              height: 90,
            ),
            SizedBox(
              height: 40,
            ),
            Stack(
              children: <Widget>[
                Padding(
                  padding:
                      const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
                  child: ImageIcon(
                    AssetImage('images/icon_phone.png'),
                    size: 24,
                    color: Color(0xff23AFDC),
                  ),
                ),
                TextFormField(
                  controller: _controllerName,
                  style: TextStyle(fontSize: 16, color: Colors.grey),
                  decoration: InputDecoration(
                      contentPadding: const EdgeInsets.fromLTRB(64, 8, 0, 8),
                      hintText: '请输入用户名',
                      hintStyle:
                          TextStyle(color: Color(0xff999999), fontSize: 16),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(36),
                          ),
                          borderSide: BorderSide(
                            color: Color(0xff999999),
                            width: 1,
                          )),
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(36),
                          ),
                          borderSide: BorderSide(
                            color: Color(0xff999999),
                            width: 1,
                          ))),
                  autofocus: false,
                ),
              ],
            ),
            SizedBox(
              height: 20,
            ),
            Stack(
              children: <Widget>[
                Padding(
                  padding:
                      const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
                  child: ImageIcon(
                    AssetImage('images/icon_pass.png'),
                    size: 24,
                    color: Color(0xff23AFDC),
                  ),
                ),
                PassField(
                  hintText: '请输入密码',
                  textEditingController: _controllerPass,
                ),
              ],
            ),
            SizedBox(
              height: 20,
            ),
//            Stack(
//              children: <Widget>[
//                Padding(
//                  padding:
//                      const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
//                  child: ImageIcon(
//                    AssetImage('images/icon_code.png'),
//                    size: 24,
//                    color: Color(0xff23AFDC),
//                  ),
//                ),
//                TextFormField(
//                  controller: _controllerCode,
//                  style: TextStyle(fontSize: 16, color: Colors.grey),
//                  keyboardType: TextInputType.number,
//                  decoration: InputDecoration(
//                      contentPadding: const EdgeInsets.fromLTRB(64, 8, 0, 8),
//                      hintText: '请输入验证码',
//                      hintStyle:
//                          TextStyle(color: Color(0xff999999), fontSize: 16),
//                      focusedBorder: OutlineInputBorder(
//                          borderRadius: BorderRadius.all(
//                            Radius.circular(36),
//                          ),
//                          borderSide: BorderSide(
//                            color: Color(0xff999999),
//                            width: 1,
//                          )),
//                      enabledBorder: OutlineInputBorder(
//                          borderRadius: BorderRadius.all(
//                            Radius.circular(36),
//                          ),
//                          borderSide: BorderSide(
//                            color: Color(0xff999999),
//                            width: 1,
//                          ))),
//                  autofocus: false,
//                ),
//                Positioned(
//                    child: Image.network(
//                      'https://flutter.io/images/homepage/header-illustration.png',
//                      width: 72,
//                      height: 28,
//                      fit: BoxFit.fill,
//                    ),
//                    right: 8,
//                    top: 4,
//                    bottom: 4),
//                //
//              ],
//            ),
            SizedBox(
              height: 30,
            ),
            MaterialButton(
              height: 40,
              minWidth: MediaQuery.of(context).size.width,
              elevation: 0,
              onPressed: () {
                Map data = Map<String, dynamic>();
                data['name'] = _controllerName.text;
                data['password'] =
                    _md5Digest(_controllerPass.text).toUpperCase();
                print(_controllerName.text);
                print(_md5Digest(_controllerPass.text));
                print(Const.BASEURL + Apis.messageLogin);
                MyDio.getInstance(url: Const.BASEURL).post(Apis.messageLogin,
                    (data) async {
                  print(data);
                  if (data == '用户名或密码错误') {
                    _scaffoldkey.currentState.showSnackBar(SnackBar(
                        elevation: 0,
                        backgroundColor: Color(0xff23AFDC),
                        content: Text(
                          data,
                          style: TextStyle(fontSize: 16),
                        )));
                  } else {
                    SharedPreferences prefs =
                        await SharedPreferences.getInstance();
                    if (data['type'] == '2') {
                      await prefs.setString('loginOrganiz', data['organiz']);
                    } else if (data['type'] == '3') {
                      await prefs.setString('loginOrganiz', data['organiz']);
                      await prefs.setString(
                          'loginSonOrganiz', data['sonOrganiz']);
                    }
                    await prefs.setString('loginType', data['type']);
                    await prefs.setString('loginAdname', data['adname']);

                    String route = '${Routes.msgManager}?pageIndex=$pageIndex';
                    Routes.router.navigateTo(context, route,
                        replace: true, transition: TransitionType.fadeIn);
                  }
                }, params: data);
              },
              child: Text(
                "立即登录",
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
              color: Color(0xff23AFDC),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(20))),
            )
          ],
        ),
      ),
    );
  }

  String _md5Digest(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }
}

class PassField extends StatefulWidget {
  final Key fieldKey;
  final String hintText;
  final String labelText;
  final String helperText;
  final TextEditingController textEditingController;

  const PassField(
      {Key key,
      this.fieldKey,
      this.hintText,
      this.labelText,
      this.helperText,
      this.textEditingController})
      : super(key: key);

  @override
  _PassFieldState createState() => _PassFieldState();
}

class _PassFieldState extends State<PassField> {
  bool _obscureText = true;

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxHeight: 36,
      ),
      child: TextFormField(
        key: widget.fieldKey,
        controller: widget.textEditingController,
        obscureText: _obscureText,
        style: TextStyle(fontSize: 16, color: Colors.grey),
        decoration: InputDecoration(
            fillColor: Colors.transparent,
            contentPadding: const EdgeInsets.fromLTRB(64, 8, 0, 8),
            filled: true,
            hintText: widget.hintText,
            hintStyle: TextStyle(color: Color(0xff999999), fontSize: 16),
            suffixIcon: GestureDetector(
              onTap: () {
                setState(() {
                  _obscureText = !_obscureText;
                });
              },
              child:
                  Icon(_obscureText ? Icons.visibility : Icons.visibility_off),
            ),
            focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(36),
                ),
                borderSide: BorderSide(
                  color: Color(0xff999999),
                  width: 1,
                )),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(36),
                ),
                borderSide: BorderSide(
                  color: Color(0xff999999),
                  width: 1,
                ))),
      ),
    );
  }
}
